import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Box, DatePicker2 } from '@alifd/next';
import { useStore } from '@/hooks';
import { observer } from 'mobx-react-lite';
import Styles from './OrdersInfo.module.scss';
import { t } from '@lingui/macro';
import dayjs from 'dayjs';
import moment from 'moment';

const RangePreset = {};
RangePreset[t`昨日`] = [dayjs(), dayjs()];
RangePreset[t`近一周`] = [dayjs().add(-7, 'day'), dayjs()];
RangePreset[t`近二周`] = [dayjs().add(-15, 'day'), dayjs()];

const _barWidth = '12%';

function OrdersInfo() {
  const chartRef = useRef(null);
  const { dashboardStore: store, ruleStore } = useStore();
  const [date, setDate] = useState([]);

  useEffect(() => {
    setDate([moment().subtract(15, 'day').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]);
  }, []);

  useEffect(() => {
    const [start, end] = date;
    const fromTime = start || moment().subtract(15, 'day').format('YYYY-MM-DD');
    const toTime = end || moment().format('YYYY-MM-DD');
    (async () => {
      const res = await store.orderGraph({ fromTime, toTime, groupId: ruleStore._group_id });
      const tempData = res;
      const chartInstance = echarts.init(chartRef.current);
      const option = {
        legend: {
          show: true,
          align: 'auto',
          data: ['订单数量', '订单金额'],
        },
        xAxis: {
          type: 'category',
          data: tempData.map((p) => p.date),
        },
        yAxis: [
          {
            type: 'value',
            name: '订单数量',
            nameTextStyle: {
              // color: '#ccc',
              fontSize: 14,
              padding: [0, 0, 10, 0],
            },
            // min: 0,
            // max: 18,
            splitNumber: 5,
            // nameLocation: 'middle',  // 将标题位置设置为中间
            nameGap: 15, // Y 轴标题和轴线之间的间距
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                width: 1,
                color: ['#ccc', '#ccc'],
              },
            },
            axisLabel: {
              show: true,
              textStyle: {
                fontSize: 12,
              },
            },
          },
          {
            // 第二个 Y 轴（汇总）
            type: 'value',
            name: '订单金额',
            // min: 0,
            // max: 6000,
            nameTextStyle: {
              // color: '#ccc',
              padding: [0, 0, 10, 0], // 只在底部添加间距
              fontSize: 14,
            },
            // nameLocation: 'middle',  // 将标题位置设置为中间
            nameGap: 15, // Y 轴标题和轴线之间的间距
            splitNumber: 5,
            offset: -5,
            alignTicks: true,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
                width: 1,
                color: ['#ccc', '#ccc'],
                overflow: 'visible',
              },
            },
            axisLabel: {
              show: true,
              textStyle: {
                fontSize: 12,
              },
            },
          },
        ],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
          textStyle: {
            color: 'black',
            align: 'left',
            fontWeight: 350,
            fontSize: 12,
          },
          backgroundColor: '#fff',
        },
        series: [
          {
            name: '订单数量',
            data: tempData.map((p) => p.orderTotalCount),
            type: 'line',
            barWidth: _barWidth,
            yAxisIndex: 0,
          },
          {
            name: '订单金额',
            data: tempData.map((p) => p.orderTotalPrice),
            type: 'line',
            barWidth: _barWidth,
            yAxisIndex: 1,
          },
        ],
      };
      chartInstance.setOption(option);
    })();
  }, [date, ruleStore._group_id]);

  /**
   * 选择时间范围事件
   * @param {*} e
   * @param {*} v
   */
  const handleOnDate = (e, v) => {
    setDate(v);
  };

  return (
    <>
      <div className={Styles.borderTop} />
      <Box style={{ padding: 20 }}>
        <Box direction="row" align="center">
          <div className={Styles.title}>{t`订单情况:`}</div>
          <DatePicker2.RangePicker
            style={{ width: 100, marginLeft: 20 }}
            onChange={handleOnDate}
            preset={RangePreset}
            value={date}
          />
        </Box>
        <div ref={chartRef} style={{ height: '450px', width: '85vw' }} />
      </Box>
    </>
  );
}

export default observer(OrdersInfo);
